package com.kanshu.ksgb.fastread.doudou.module.book.presenter;

import android.util.Log;

import com.google.gson.reflect.TypeToken;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver;
import com.kanshu.ksgb.fastread.doudou.common.util.DiskLruCacheUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.RecentBookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShelfTopData;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.WrapBookInfos;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.ShelfService;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.ShelfRequestParams;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by wcy on 2017\6\19 0019.
 */

public class ShelfModel {

    List<Disposable> mDisposables = new ArrayList<>();

    /**
     * 获取最近阅读信息
     *
     * @param params
     * @param callback
     */
    public void getRecentInfos(final ShelfRequestParams params, final INetCommCallback<BaseResult<List<RecentBookInfo>>> callback) {
        if (!NetUtils.isNetworkAvailable(Xutils.getContext())) {
            callback.onError(Constants.ErrCode.NetErr, "no net");
            return;
        }
        RetrofitHelper helper = RetrofitHelper.getInstance();
        helper.createService(ShelfService.class)
                .getRecentInfos(params, "1")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io()).subscribe(new BaseObserver<List<RecentBookInfo>>() {
            @Override
            public void onResponse(BaseResult<List<RecentBookInfo>> listBaseResult, List<RecentBookInfo> recentBookInfos, Disposable disposable) {
                if (listBaseResult.result.status.code != 0) {
                    callback.onError(listBaseResult.result.status.code, "no net");
                    return;
                }
                mDisposables.add(disposable);
                if (BaseResult.isNotNull(listBaseResult)) {
                    callback.onResponse(listBaseResult);
                }
            }

            @Override
            public void onError(int code, String errDesc) {
                super.onError(code, errDesc);
                if (mDisposable.isDisposed()) {
                    return;
                }
                callback.onError(Constants.ErrCode.UnknowErr, errDesc);
            }
        });
    }


    /**
     * 获取最近阅读信息
     *
     * @param params
     * @param callback
     */
    public void getRecentTopInfos(final ShelfRequestParams params, final INetCommCallback<BaseResult<ShelfTopData>> callback) {
        RetrofitHelper helper = RetrofitHelper.getInstance();
        helper.createService(ShelfService.class)
                .getShelfBookTop(params, "1")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io()).subscribe(new BaseObserver<ShelfTopData>() {
            @Override
            public void onError(int code, String errDesc) {
                super.onError(code, errDesc);
                if (mDisposable.isDisposed()) {
                    return;
                }
                callback.onError(Constants.ErrCode.UnknowErr, errDesc);
            }

            @Override
            public void onResponse(BaseResult<ShelfTopData> info, ShelfTopData shelfTopData, Disposable disposable) {
                if (mDisposable.isDisposed()) {
                    return;
                }
                if (info.result.status.code != 0) {
                    callback.onError(info.result.status.code, "no net");
                    return;
                }
                mDisposables.add(disposable);
                if (BaseResult.isNotNull(info)) {
                    callback.onResponse(info);
                }
            }
        });
    }


    /**
     * 获取我的收藏的信息
     *
     * @param key
     * @param callback
     */
    public void getShelfBookList(final String key, final INetCommCallback<WrapBookInfos> callback) {
        Type type = new TypeToken<ArrayList<BookInfo>>() {
        }.getType();
        final WrapBookInfos wrap = new WrapBookInfos();
        // 本地缓存数据
        List<BookInfo> bookInfos = DiskLruCacheUtils.get(key, type);
        wrap.isFromNet = false;
        wrap.bookInfos = bookInfos;
        if (!Utils.isEmptyList(bookInfos)) {
            callback.onResponse(wrap);
        }
        // 加载网络数据
        RetrofitHelper helper = RetrofitHelper.getInstance();
        ShelfRequestParams params = new ShelfRequestParams();
        params.page = 1;
        helper.createService(ShelfService.class)
                .getShelfBookList(params, "1")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io()).subscribe(new BaseObserver<List<BookInfo>>() {
            @Override
            public void onError(int code, String errDesc) {
                super.onError(code, errDesc);
                if (mDisposable.isDisposed()) {
                    return;
                }
                callback.onError(code, errDesc);
            }

            @Override
            public void onResponse(BaseResult<List<BookInfo>> listBaseResult, List<BookInfo> bookInfos, Disposable disposable) {
                if (mDisposable.isDisposed()) {
                    return;
                }
                if (listBaseResult.result.status.code != 0) {
                    callback.onError(listBaseResult.result.status.code, "no net");
                    return;
                }
                WrapBookInfos wrapBookInfos = new WrapBookInfos();
                wrapBookInfos.isFromNet = true;
                wrapBookInfos.bookInfos = bookInfos;
                //DiskLruCacheUtils.put(key, bookInfos);
                callback.onResponse(wrapBookInfos);
            }
        });
    }


    /**
     * 删除书籍
     *
     * @param book_ids
     * @param callback
     */
    public void deleteRecentBook(String book_ids, final INetCommCallback<List<String>> callback) {
        if (!NetUtils.isNetworkAvailable(Xutils.getContext())) {
            callback.onError(Constants.ErrCode.NetErr, "no net");
            return;
        }
        RetrofitHelper helper = RetrofitHelper.getInstance();
        helper.createService(ShelfService.class)
                .deleteRecentBook(book_ids)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io()).subscribe(new Observer<ResponseBody>() {
            Disposable mDisposable;

            @Override
            public void onSubscribe(Disposable d) {
                mDisposables.add(d);
                mDisposable = d;
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                if (mDisposable.isDisposed()) {
                    return;
                }
                String s = null;
                try {
                    s = responseBody.string();
                    JSONObject object = new JSONObject(s);
                    JSONObject result = object.getJSONObject("result");
                    JSONObject status = result.getJSONObject("status");
                    int code = status.getInt("code");
                    String str = status.getString("msg");
                    JSONArray data = result.getJSONArray("data");
                    Type type = new TypeToken<List<String>>() {
                    }.getType();
                    Log.d("wcy", "delrecentbook:" + s);
                    if (code == 0) {
                        callback.onResponse((List<String>) JsonUtils.json2Bean(data.toString(), type));
                    } else {
                        callback.onError(code, str);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                if (mDisposable.isDisposed()) {
                    return;
                }
                callback.onError(-1, "no data");
            }

            @Override
            public void onComplete() {
            }
        });
    }

    public void cancel() {
        Utils.dispose(mDisposables);
    }
}
